<?php

class Model_UserGroup extends Model{
	
	public $hashPrivilege;
	
	
	function __construct(){
    	parent::__construct();
    	$this->hashPrivilege = Helper_Array::to_hashmap(M("UserPrivilegeName")->select('name,description'),'name','description');
    }
	
    /**
     *在读取每个用户组后，读取该用户组的用户数量
     * @param array &$row
     * 
     **/
	protected function _after_select_fetch(&$row){
		if(!isset($row['id'])) return;
		
		//使用static缓存数据
		static $userQty = null;
		
		if(null == $userQty){
			$data = $this->select("count(*) as `qty`, groupid","group by groupid","user");
			$userQty = Helper_Array::to_hashmap($data,'groupid','qty');
		
		}
		$row['_userqty'] = intval($userQty[$row['id']]);
	}
	
	public function getHash(){
		static $_cache = null;
		
		if($_cache == null){
			$_cache = Helper_Array::to_hashmap($this->select("*","where 1 order by `groupname`"),'id','groupname');
		}
		return $_cache;
	}
	
	public function remove($ids){
		if(!is_array($ids)){
			$ids = split(",",$ids);
		}
		$cnt = 0;
		foreach ($ids as $id){
			$counter = M("User")->selectCount("where `groupid` in ($id)");
			if ($counter > 0) {
				throw new GiException("请首先删除用户组下的所有用户，然后再删除分组。");
			}else{
				parent::remove($id);
				M("UserPrivilege")->removeGroupPrivilege($id);
			}
			$cnt++;			

		}
		return $cnt; 
		
	}
	
	public function save($data){
		$id = parent::save($data);
		empty($data['id']) && $data['id'] = $id;
		return M("UserPrivilege")->saveGroupPrivilege($data[id],$data['privilege']);
	}
}
?>